package com.academic.system.service.impl;

import com.academic.common.core.domain.entity.SysExam;
import com.academic.common.core.domain.entity.UserExam;
import com.academic.common.core.page.TableDataInfo;
import com.academic.system.domain.rep.ExamRep;
import com.academic.system.domain.req.NewReq;
import com.academic.system.mapper.dao.SysExamDao;
import com.academic.system.mapper.dao.UserExamDao;
import com.academic.system.service.SysExamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (SysExam)表服务实现类
 *
 * @author makejava
 * @since 2024-10-31 22:55:00
 */
@Service("sysExamService")
public class SysExamServiceImpl extends ServiceImpl<SysExamDao, SysExam> implements SysExamService {

    private final SysExamDao sysExamDao;
    private final UserExamDao userExamDao;
    private final SysBookServiceImpl sysBookService;

    public SysExamServiceImpl(SysExamDao sysExamDao, UserExamDao userExamDao, SysBookServiceImpl sysBookService) {
        this.sysExamDao = sysExamDao;
        this.userExamDao = userExamDao;
        this.sysBookService = sysBookService;
    }

    @Override
    public TableDataInfo getExamHistory(NewReq newReq) {
        PageHelper.startPage(newReq.getPageNum(), newReq.getPageSize());
        List<ExamRep> reps = new ArrayList<>();
        QueryWrapper<UserExam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", newReq.getId());
        List<UserExam> userExams = userExamDao.selectList(queryWrapper);
        PageInfo<UserExam> pageInfo = new PageInfo<>(userExams);
        List<Long> examIds = userExams.stream()
                .map(UserExam::getExamId)
                .collect(Collectors.toList());
        QueryWrapper<SysExam> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id", examIds);
        List<SysExam> sysExams = sysExamDao.selectList(queryWrapper1);
        for (UserExam userExam : userExams) {
            ExamRep examRep = new ExamRep();
            SysExam sysExam = sysExams.stream()
                    .filter(exam -> exam.getId()
                            .equals(userExam.getExamId()))
                    .findFirst()
                    .get();
            examRep.setExamName(sysExam.getExamName());
            examRep.setCategory(sysExam.getCategory());
            examRep.setExamTime(userExam.getExamTime());
            examRep.setStatusExam(userExam.getStatusExam());
            examRep.setStatusRead(userExam.getStatusRead());
            examRep.setClassroom(userExam.getClassroom());
            reps.add(examRep);
        }
        return sysBookService.getDataTable(reps,pageInfo.getTotal());
    }
}

